package com.neusoft.bigdata.hbase.biz.impl;

import java.util.Calendar;
import java.util.Map;

import com.neusoft.bigdata.hbase.biz.AbstractHBaseBiz;
import com.neusoft.bigdata.hbase.biz.MonitorBoss;
import com.neusoft.bigdata.hbase.biz.MonitorService;
import com.neusoft.bigdata.hbase.biz.StatisticService;
import com.neusoft.bigdata.hbase.model.MetricData;
import com.neusoft.bigdata.hbase.model.StaticMetricData;

/**
 * 监控数据查询顶层接口
 * 
 * @author lihzh
 * @date 2012-11-21 下午6:27:01
 */
public class MonitorBossImpl extends AbstractHBaseBiz implements MonitorBoss {

	private StatisticService statisticService = new StatisticServiceHBaseImpl();
	private MonitorService monitorService = new MonitorServiceHBaseImpl();

	/**
	 * 目前写死实现2天和和7天
	 */
	@Override
	public Map<String, MetricData> searchMetrics(String fqn, long endTime,
			int timeRange) {
		// 获取当前小时的整点数据
		long hourPoint = getHourPoint(endTime);
		// 获取起始的小时，整点。
		Calendar startTimeCalendar = getHiveDayRangeCalendar(hourPoint,
				timeRange);
		long startTime = startTimeCalendar.getTimeInMillis();
		StaticMetricData statisticMetricData = statisticService.findData(fqn,
				startTime, hourPoint);
		long lastStaticTime = statisticMetricData.getLastDataTime();
		Map<String, MetricData> monitorDataMap = monitorService
				.getDataByFQNAndTimeRange(fqn, lastStaticTime, hourPoint);
		monitorDataMap.get(COLUMN_NAME_CPULOAD).addAllDataPoint(
				statisticMetricData.getMetricDataMap().get(COLUMN_NAME_CPULOAD)
						.getDataPoints());
		monitorDataMap.get(COLUMN_NAME_MEMORYUSAGE).addAllDataPoint(
				statisticMetricData.getMetricDataMap()
						.get(COLUMN_NAME_MEMORYUSAGE).getDataPoints());
		return monitorDataMap;
	}

	/**
	 * 获取当前时间的整点时间
	 * 
	 * @param currentTime
	 * @return
	 * @author lihzh
	 * @date 2012-11-22 下午1:09:58
	 */
	private long getHourPoint(long currentTime) {
		Calendar currentTimeCalendar = Calendar.getInstance();
		currentTimeCalendar.setTimeInMillis(currentTime);
		currentTimeCalendar.set(Calendar.MINUTE, 0);
		currentTimeCalendar.set(Calendar.SECOND, 0);
		currentTimeCalendar.set(Calendar.MILLISECOND, 0);
		return currentTimeCalendar.getTimeInMillis();
	}

	private Calendar getHiveDayRangeCalendar(long endTime, int dayBefore) {
		Calendar startTimeCalendar = Calendar.getInstance();
		startTimeCalendar.setTimeInMillis(endTime);
		startTimeCalendar.add(Calendar.DAY_OF_MONTH, dayBefore * (-1));
		return startTimeCalendar;
	}

}
